/**
 * 扫描结果弹窗
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Tag, Card, Overlay, Balloon } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import utils from 'utils';
import docs from 'utils/docs';
import exceed from 'utils/apimap';
import { ENUM } from 'utils/constants.js';
import { navigateOpen } from 'utils/router';
import ListLoading from 'atComponents/ListLoading';
import BuildResultIssues from '../buildResultIssues';
import DependencyBuildResultIssues from '../dependencyBuildResultIssues';
import './index.scss';
import intl from '../../locale';

const STATE_ENUM = ENUM.checkState;
const SCAN_STATE_ENUM = ENUM.scanState;
const { Popup } = Overlay;

// 触发文案
const { triggerText } = ENUM;
export default class BuildResultDialog extends React.Component {
  static propTypes = {
    build: PropTypes.object,
    projectId: PropTypes.number,
    isNeedRestart: PropTypes.bool,
  };

  static defaultProps = {
    build: null,
    projectId: window.FORCE.pathResource ? window.FORCE.pathResource.id : null,
    isNeedRestart: false,
  };

  constructor(props) {
    super(props);
    this.dialog = React.createRef();
  }

  state = {
    issues: [],
    isLoadingIssues: true,
    issueFilter: '', // 顶部的问题过滤器
  };

  componentDidMount() {
    this.fetchIssues();
  }

  onClose = () => {
    this.props.close();
  };

  fetchIssues() {
    const { build, projectId } = this.props;
    let data = {};
    if (
      build.task_name ===
      intl.get({
        id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
        defaultMessage: '依赖包漏洞检测',
      })
    ) {
      data = { issue_type: 'indirect_dependency' };
    }

    exceed
      .fetch({
        api: 'projects.builds.issues',
        params: { projectId, buildId: build.id },
        data,
      })
      .then((result) => {
        result.shift();
        this.setState({
          issues: result,
          isLoadingIssues: false,
        });
      })
      .fail(console.log);
  }

  // 遗留问题，没什么作用，未防止报错，留下函数定义
  forceUpdateDialog = () => {
    // this.dialog.current.forceUpdate();
  };

  renderBuildResultIssues = () => {
    const { build, projectId, isNeedRestart } = this.props;
    const { issues, issueFilter } = this.state;
    if (
      build.task_name ===
      intl.get({
        id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
        defaultMessage: '依赖包漏洞检测',
      })
    ) {
      return (
        <DependencyBuildResultIssues
          isNeedRestart={isNeedRestart}
          onClose={this.onClose}
          issues={issues}
          build={build}
          issueFilter={issueFilter}
          projectId={projectId}
          forceUpdateDialog={this.forceUpdateDialog}
        />
      );
    } else {
      return (
        <BuildResultIssues
          isNeedRestart={isNeedRestart}
          onClose={this.onClose}
          issues={issues}
          build={build}
          issueFilter={issueFilter}
          projectId={projectId}
          forceUpdateDialog={this.forceUpdateDialog}
        />
      );
    }
  };

  goIssueList = () => {
    const { pathResource, resourceSubject } = window.FORCE;
    const { build } = this.props;
    const securityPageName =
      build.task_name ===
      intl.get({
        id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
        defaultMessage: '依赖包漏洞检测',
      })
        ? 'dependency_analysis'
        : 'sensitive_info';
    navigateOpen(
      `/${pathResource.fullPath}/project_security/${securityPageName}/${resourceSubject.revision}`,
      '_blank',
    );
  };

  render() {
    const { build } = this.props;
    const { isLoadingIssues, issueFilter } = this.state;
    const {
      task_name,
      state,
      gmt_create,
      trigger_user,
      sha,
      mode,
      total_file_count,
      issue_file_count,
      ignored_file_num,
      whitelist,
      blocker_count,
      critical_count,
      major_count,
    } = build;

    const hasWhitelist =
      [
        intl.get({
          id: 'code-assets.components.buildResultDialog.SensitiveInformationScanning',
          defaultMessage: '敏感信息扫描',
        }),
      ].indexOf(task_name) >= 0;

    const whitelistLines = whitelist ? whitelist.split('\n') : null;

    // 统计文案区分
    let totalText = '';
    const totalDesc =
      task_name ===
      intl.get({
        id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
        defaultMessage: '依赖包漏洞检测',
      })
        ? intl.get(
            {
              id: 'code-assets.components.buildResultDialog.IssuefilecountRiskDependencies',
              defaultMessage: '共 {issueFileCount} 个风险依赖项',
            },
            { issueFileCount: issue_file_count },
          )
        : intl.get(
            {
              id: 'code-assets.components.buildResultDialog.TotalfilecountFilesScanned',
              defaultMessage: '已扫描 {totalFileCount} 个文件',
            },
            { totalFileCount: total_file_count },
          );
    if (mode === 'MERGE_REQUEST') {
      totalText =
        task_name ===
        intl.get({
          id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
          defaultMessage: '依赖包漏洞检测',
        })
          ? intl.get({
              id: 'code-assets.components.buildResultDialog.IncrementalAnalysis',
              defaultMessage: '增量分析',
            })
          : intl.get({
              id: 'code-assets.components.buildResultDialog.IncrementalScan',
              defaultMessage: '增量扫描',
            });
    } else {
      totalText =
        task_name ===
        intl.get({
          id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
          defaultMessage: '依赖包漏洞检测',
        })
          ? intl.get({
              id: 'code-assets.components.buildResultDialog.FullAnalysis',
              defaultMessage: '全量分析',
            })
          : intl.get({
              id: 'code-assets.components.buildResultDialog.FullScan',
              defaultMessage: '全量扫描',
            });
    }
    return (
      <Dialog
        title={
          <div className="build-result-dialog-title">
            <span>{task_name}</span>
            {/* {task_name ===
              intl.get({
                id: 'code-assets.components.buildResultDialog.SensitiveInformationScanning',
                defaultMessage: '敏感信息扫描',
              }) && (
              <Button type="primary" text className="go-list" onClick={this.goIssueList}>
                {intl.get({
                  id: 'code-assets.components.buildResultDialog.ManageQuestions',
                  defaultMessage: '管理问题列表',
                })}
              </Button>
            )}
            {task_name ===
              intl.get({
                id: 'code-assets.components.buildResultDialog.DependencyPackageVulnerabilityDetection',
                defaultMessage: '依赖包漏洞检测',
              }) && (
              <Button type="primary" text className="go-list" onClick={this.goIssueList}>
                {intl.get({
                  id: 'code-assets.components.buildResultDialog.DependencyList',
                  defaultMessage: '依赖关系列表',
                })}
              </Button>
            )} */}
          </div>
        }
        visible
        className="build-result-dialog"
        style={{ width: 800, minHeight: '224px', overflowY: 'auto' }}
        onCancel={this.onClose}
        onClose={this.onClose}
        footer={false}
        isFullScreen
        id="build-dialog"
        ref={this.dialog}
      >
        <div>
          <div className="build-header">
            <Tag
              color={SCAN_STATE_ENUM[state].color}
              icon={
                <img
                  src="https://img.alicdn.com/tfs/TB1zOIKd5DsXe8jSZR0XXXK6FXa-352-272.png"
                  alt=""
                />
              }
              className={'builds-result-tag'}
            >
              {intl.get({
                id: 'code-assets.components.buildResultDialog.Detection',
                defaultMessage: '检测',
              })}

              {STATE_ENUM[state].text}
            </Tag>
            <span className="build-header-trigger-msg">
              {' '}
              {intl.get({
                id: 'code-assets.components.buildResultDialog.ScanResultsBasedOnSubmission',
                defaultMessage: '扫描结果基于提交',
              })}{' '}
              {sha.slice(0, 8)}
            </span>
            <span className="build-header-tail-trigger-msg">
              {trigger_user.name}
              {intl.get({
                id: 'code-assets.components.buildResultDialog.In',
                defaultMessage: '于',
              })}
              {utils.getBeautyTime(gmt_create)}
              <span> {triggerText[mode] || triggerText.default}</span>
            </span>
          </div>
          <div className="build-summary">
            <div className="build-summary-total">
              <div className="build-summary-total-title">{totalText}</div>

              {hasWhitelist ? (
                <div className="build-summary-total-cnt-card">
                  <div className="build-summary-total-cnt">
                    {intl.get(
                      {
                        id: 'code-assets.components.buildResultDialog.TotalTotalfilecountFiles',
                        defaultMessage: '总计 {totalFileCount} 个文件',
                      },
                      { totalFileCount: total_file_count },
                    )}
                  </div>
                  <div className="build-summary-total-cnt">
                    {intl.get({
                      id: 'code-assets.components.buildResultDialog.Skip',
                      defaultMessage: '跳过',
                    })}
                    {ignored_file_num || 0}
                    {intl.get({
                      id: 'code-assets.components.buildResultDialog.Files',
                      defaultMessage: '个文件',
                    })}
                    <Popup
                      trigger={
                        <YunxiaoIcon
                          type="question-line"
                          className="build-summary-whitelist-icon"
                          size="small"
                        />
                      }
                      triggerType="hover"
                      showTitleBullet={false}
                    >
                      <Card
                        className="build-summary-whitelist"
                        title={intl.get({
                          id: 'code-assets.components.buildResultDialog.FileWhitelistRules',
                          defaultMessage: '文件白名单规则',
                        })}
                        contentHeight="auto"
                        extra={
                          <a href={docs('fileWhitelistRules')} target="_blank" rel="noreferrer">
                            {intl.get({
                              id: 'code-assets.components.buildResultDialog.LearnMore',
                              defaultMessage: '了解更多',
                            })}
                          </a>
                        }
                      >
                        <div className="build-summary-whitelist-details">
                          {whitelistLines ? (
                            whitelistLines.map((line) => {
                              return <div className="build-summary-whitelist-item">{line}</div>;
                            })
                          ) : (
                            <div className="build-summary-whitelist-item">
                              {intl.get({
                                id: 'code-assets.components.buildResultDialog.NoRulesAreConfigured',
                                defaultMessage: '暂未配置规则',
                              })}
                            </div>
                          )}
                        </div>
                      </Card>
                    </Popup>
                  </div>
                </div>
              ) : (
                <div className="build-summary-total-cnt-card">
                  <div className="build-summary-total-cnt">{totalDesc}</div>
                </div>
              )}
            </div>
            <div className="build-summary-detail">
              <div
                className={`build-summary-item ${issueFilter === '' ? 'active' : null}`}
                onClick={() => {
                  this.setState({ issueFilter: '' });
                }}
              >
                <div className="build-summary-item-cnt">
                  {blocker_count + critical_count + major_count}
                </div>
                <div className="build-summary-item-title">
                  {intl.get({
                    id: 'code-assets.components.buildResultDialog.AllQuestions',
                    defaultMessage: '所有问题',
                  })}

                  {(task_name ===
                    intl.get({
                      id: 'code-assets.components.buildResultDialog.SensitiveInformationScanning',
                      defaultMessage: '敏感信息扫描',
                    }) ||
                    task_name ===
                      intl.get({
                        id: 'code-assets.components.buildResultDialog.JavaDevelopmentProtocol',
                        defaultMessage: 'Java开发规约',
                      })) &&
                    blocker_count + critical_count + major_count > 100 && (
                      <Balloon.Tooltip
                        trigger={
                          <ButtonIcon
                            type="secondary"
                            name="information-line"
                            style={{ marginLeft: 4, display: 'inline-block', color: '#fa8c15' }}
                          />
                        }
                        align="t"
                      >
                        {intl.get({
                          id: 'code-assets.components.buildResultDialog.TheNumberOfUnresolvedIssues',
                          defaultMessage: '当前未解决问题数已超过上限 100 条，修复后可查看更多问题',
                        })}
                      </Balloon.Tooltip>
                    )}
                </div>
              </div>
              <div
                className={`build-summary-item ${issueFilter === 'blocker' ? 'active' : null}`}
                onClick={() => {
                  this.setState({ issueFilter: 'blocker' });
                }}
              >
                <div className="build-summary-item-cnt" style={{ color: '#e84738' }}>
                  {blocker_count}
                </div>
                <div className="build-summary-item-title" style={{ color: '#e84738' }}>
                  Blocker
                </div>
              </div>
              <div
                className={`build-summary-item ${issueFilter === 'critical' ? 'active' : null}`}
                onClick={() => {
                  this.setState({ issueFilter: 'critical' });
                }}
              >
                <div className="build-summary-item-cnt" style={{ color: '#f98e1b' }}>
                  {critical_count}
                </div>
                <div className="build-summary-item-title" style={{ color: '#f98e1b' }}>
                  Critical
                </div>
              </div>
              <div
                className={`build-summary-item ${issueFilter === 'major' ? 'active' : null}`}
                onClick={() => {
                  this.setState({ issueFilter: 'major' });
                }}
              >
                <div className="build-summary-item-cnt" style={{ color: '#1b9aee' }}>
                  {major_count}
                </div>
                <div className="build-summary-item-title" style={{ color: '#1b9aee' }}>
                  Major
                </div>
              </div>
            </div>
          </div>
          <div className="build-issues">
            {!isLoadingIssues ? this.renderBuildResultIssues() : <ListLoading />}
          </div>
        </div>
      </Dialog>
    );
  }
}
